package com.building.hcrm.ui;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

import com.building.hcrm.R;
import com.building.hcrm.base.BaseActivity;
import com.building.hcrm.base.BaseAsyncTask;
import com.building.hcrm.base.BaseStaffSelector.SelectedStaffListener;
import com.building.hcrm.common.ComConst;
import com.building.hcrm.common.ComFunc;
import com.building.hcrm.common.User;
import com.building.hcrm.common.Utils;
import com.building.hcrm.model.AchmetLog;
import com.building.hcrm.model.SysUser;
import com.building.hcrm.ui.customcontrols.ComStaffSelector;
import com.building.hcrm.wcf.KpiServiceProxy;

public class KpiListActivity extends BaseActivity
{
	private int iCount = 0;
	private Button _btnDateFrom;
	private Button _btnDateTo;
	private ComStaffSelector _selector;
	private ListView _lstv;
	private ImageButton _imgBtnTitleRight;
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_kpi_list);
		InitTitle();
		_selector = (ComStaffSelector) findViewById(R.id.staff_selector);
		_selector.load(ComStaffSelector.DISPLAY_TYPE_ALL, User.getInstance(this));
		FromToTimer(null, null);
		_lstv = (ListView) findViewById(R.id.kpi_record_list);
		_selector.setOnSelectedStaffListener(selectedStaffListener);
		_lstv.setOnItemClickListener(listItemClickListener);
	}
	
	private void InitTitle()
	{
		imgbtnHome = (ImageButton) findViewById(R.id.imgbtn_home);
		imgbtnHome.setOnClickListener(new View.OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				finish();
			}
		});
		setTitle(getString(R.string.kpi_list_title));
		_imgBtnTitleRight = (ImageButton) findViewById(R.id.imgbtn_save);
		_imgBtnTitleRight.setVisibility(View.INVISIBLE);
	}
	
	private void FromToTimer(Date dtFrom, Date dtTo)
	{
		try
		{
			Calendar calendar = Calendar.getInstance();
			SimpleDateFormat sdfdate;

			_btnDateFrom = (Button) findViewById(R.id.btn_date_selector_from);
			_btnDateFrom.setOnClickListener(DatePickerButtion_Click);
			sdfdate = new SimpleDateFormat(ComConst.DATE_FORMAT, Locale.getDefault());
			_btnDateFrom.setText(sdfdate.format(dtFrom == null ? calendar.getTime() : dtFrom));

			_btnDateTo = (Button) findViewById(R.id.btn_date_selector_to);
			_btnDateTo.setOnClickListener(DatePickerButtion_Click);
			sdfdate = new SimpleDateFormat(ComConst.DATE_FORMAT, Locale.getDefault());
			_btnDateTo.setText(sdfdate.format(dtTo == null ? calendar.getTime() : dtTo));

		}
		catch (Exception e)
		{
			Log.e(LTAG, ComFunc.getExceptionMessage(e), e);
		}
	}

	// 日期选择事件监听：OnClickListener
	private View.OnClickListener DatePickerButtion_Click = new View.OnClickListener()
	{
		@Override
		public void onClick(View v)
		{
			try
			{
				if (Utils.isFastDoubleClick())
					return;
				final Button button = (Button) v;

				// 日期設定
				Calendar calendar = Calendar.getInstance();
				int year = calendar.get(Calendar.YEAR);
				int monthOfYear = calendar.get(Calendar.MONTH);
				int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
				if (button.getText().length() > 0)
				{
					year = Integer.parseInt(button.getText().toString().split(ComConst.DATE_SEPARATOR)[0]);
					monthOfYear = Integer.parseInt(button.getText().toString().split(ComConst.DATE_SEPARATOR)[1]) - 1;
					dayOfMonth = Integer.parseInt(button.getText().toString().split(ComConst.DATE_SEPARATOR)[2]);
				}

				// 日付選択ﾀﾞｲｱﾛｸﾞ：OnDateSetListener
				DatePickerDialog.OnDateSetListener dateSetListener = new DatePickerDialog.OnDateSetListener()
				{
					private int _year, _monthOfYear, _dayOfMonth;

					@Override
					public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth)
					{
						try
						{
							if (_year != year || _monthOfYear != monthOfYear || _dayOfMonth != dayOfMonth)
							{
								_year = year;
								_monthOfYear = monthOfYear;
								_dayOfMonth = dayOfMonth;
								Calendar calendar = Calendar.getInstance();
								calendar.set(year, monthOfYear, dayOfMonth);
								SimpleDateFormat sdf = new SimpleDateFormat(ComConst.DATE_FORMAT, Locale.getDefault());
								Date dtCheck = new Date(sdf.format(calendar.getTime()));
								if (CheckDateValue(button, dtCheck))
								{
									button.setText(sdf.format(calendar.getTime()));
									DataBind();
								}
							}
						}
						catch (Exception e)
						{
							Log.e(LTAG, ComFunc.getExceptionMessage(e), e);
						}
					}

				};

				// 日付選択ﾀﾞｲｱﾛｸﾞ作成＆表示
				DatePickerDialog datePickerDialog = new DatePickerDialog(v.getContext(), dateSetListener, year,
						monthOfYear, dayOfMonth);
				datePickerDialog.show();
			}
			catch (Exception e)
			{
				Log.e(LTAG, ComFunc.getExceptionMessage(e), e);
			}
		}
	};

	private boolean CheckDateValue(Button button, Date checkDate)
	{
		Date compareDate = null;
		String alarmText = null;

		// 触发控件为起始时间
		if (button.getId() == _btnDateFrom.getId())
		{
			compareDate = new Date(_btnDateTo.getText().toString());
			if (checkDate.after(compareDate))
			{
				alarmText = "起始时间必须小于或等于结束时间";
				Toast.makeText(this, alarmText, Toast.LENGTH_SHORT).show();
				return false;
			}
		}
		else if (button.getId() == _btnDateTo.getId())
		{
			compareDate = new Date(_btnDateFrom.getText().toString());
			if (checkDate.before(compareDate))
			{
				alarmText = "结束时间必须大于或等于起始时间";
				Toast.makeText(this, alarmText, Toast.LENGTH_SHORT).show();
				return false;
			}
		}

		return true;
	}

	
	private SelectedStaffListener selectedStaffListener = new SelectedStaffListener()
	{
		@Override
		public void onSelectedStaff(SysUser inStaff)
		{
			if (null != inStaff)
			{
				DataBind();
			}
		}
	};
	
	private void DataBind()
	{
		SysUser sysUser = null;
		do
		{
			try
			{
				sysUser = _selector.getCurrentStaff();
			}
			catch (Exception e)
			{
				Log.e(LTAG, ComFunc.getExceptionMessage(e), e);
			}
		}
		while (null == sysUser && iCount < 99);

		new BaseAsyncTask<String, String, List<AchmetLog>>(KpiListActivity.this)
		{
			@Override
			protected void onPreExecute()
			{
				super.onPreExecute();
			}

			@Override
			protected List<AchmetLog> doInBackground(String... params)
			{
				List<AchmetLog> re = null;
				if (null != params && params.length > 2)
				{
					try
					{
						re = KpiServiceProxy.getInstance(KpiListActivity.this).AchmetLogOfUser(params[0], params[1],params[2]);
					}
					catch (Exception e)
					{
						Log.e(LTAG, ComFunc.getExceptionMessage(e), e);
					}
				}
				return re;
			}

			@Override
			protected void onPostExecute(List<AchmetLog> result)
			{
				super.onPostExecute(result);
				setListView(result);
			}
		}.execute(sysUser.getUserNum(),_btnDateFrom.getText().toString(),_btnDateTo.getText().toString());
	}

	private void setListView(List<AchmetLog> param)
	{
		List<HashMap<String, Object>> lstHm = new ArrayList<HashMap<String, Object>>();
		if (null != param)
		{
			for (AchmetLog item : param)
			{
				boolean bHas = false;
				for(HashMap<String, Object> hm : lstHm)
				{
					if (hm.get("Time").equals(item.AchmetTime))
					{
						hm.put("totalScore", Float.valueOf(hm.get("totalScore").toString()) + item.AchmetScore);
						List<AchmetLog> lst = (List<AchmetLog>) hm.get("AchmetLogList");
						lst.add(item);
						hm.put("AchmetLogList", lst);
						bHas = true;
						break;
					}
				}
				if (!bHas)
				{
					HashMap<String, Object> hashMap = new HashMap<String, Object>();
					hashMap.put("Time", item.AchmetTime);
					hashMap.put("TimeDisplay", ComFunc.GetStringByDate(item.AchmetTime, ComConst.DATE_FORMAT));
					hashMap.put("totalScore", item.AchmetScore);
					List<AchmetLog> lst = new ArrayList<AchmetLog>();
					lst.add(item);
					hashMap.put("AchmetLogList", lst);
					lstHm.add(hashMap);
				}
			}
		}
		SimpleAdapter sAdapter = new SimpleAdapter(this, lstHm, R.layout.list_item_kpi, new String[] { "TimeDisplay",
				"totalScore"}, new int[] { R.id.txtKpiDate, R.id.txtScore});

		_lstv.setAdapter(sAdapter);
	}
	
	private OnItemClickListener listItemClickListener = new OnItemClickListener()
	{
		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
		{
			if (arg2 >= 0)
			{
				Intent intent = null;
				intent = new Intent(getApplicationContext(), KpiEditActivity.class);
				intent.putExtra("AchmetIns", (HashMap<String, Object>)_lstv.getItemAtPosition(arg2));
				intent.putExtra(ComConst.INTENT_EXTRA_SYSUSER, _selector.getCurrentStaff());
				startActivity(intent);
			}
		}
	};
}
